import mimetypes

from urllib.parse import quote
from uuid import UUID

from fastapi import APIRouter, File, UploadFile, Depends, Form
from fastapi.responses import FileResponse

from core.database import get_db
from service.bid_service import BidService
from schema.all import DELETEResponse, POSTResponse

router = APIRouter()

@router.get(path="/{bid_id}/file", response_class=FileResponse, summary="下载一份投标文件")
async def get_bid_file(
    bid_id: UUID,
    db=Depends(get_db),
):
    service = BidService(db)
    bid_info = await service.get_document_by_id(bid_id)
    encoded_file_name = quote(bid_info.file_name)
    media_type = mimetypes.guess_type(encoded_file_name)[0]
    return FileResponse(
        path=bid_info.file_path,
        media_type=media_type,
        headers={
            "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_file_name}"
        },
    )

@router.post("/{bid_id}/bargaining", response_model=POSTResponse, summary="上传一份二次议价文件")
async def upload_bid_bargaining_file(
    bid_id: UUID,
    file: UploadFile = File(...),
    db=Depends(get_db),
):
    service = BidService(db)
    await service.update_bargaining(bid_id, file)
    return POSTResponse(message="二次议价文件上传成功")

@router.get(
    path="/{bid_id}/bargaining/file",
    response_class=FileResponse,
    summary="下载一份二次议价文件",
)
async def get_bid_bargaining_file(
    bid_id: UUID,
    db=Depends(get_db),
):
    service = BidService(db)
    bid_info = await service.get_bargaining_by_id(bid_id)
    encoded_file_name = quote(bid_info.file_name)
    media_type = mimetypes.guess_type(encoded_file_name)[0]
    return FileResponse(
        path=bid_info.file_path,
        media_type=media_type,
        headers={
            "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_file_name}"
        },
)

@router.delete("/{bid_id}/bargaining", response_model=DELETEResponse, summary="删除一份二次议价文件")
async def delete_bid_bargaining_file(
    bid_id: UUID,
    db=Depends(get_db),
):
    service = BidService(db)
    result = await service.delete_bargaining(bid_id)
    return DELETEResponse(message="二次议价文件删除成功")


@router.delete("/{bid_id}", response_model=DELETEResponse, summary="删除一份投标文件")
async def delete_bid_file(
    bid_id: UUID,
    db=Depends(get_db),
):
    service = BidService(db)
    await service.delete_bid(bid_id)
    return DELETEResponse(message="投标文件删除成功")